import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import authRoutes from "./routes/auth";
import uploadRoutes from "./routes/upload";
import { initDbRoutes } from "./services/dbService";
import { corsMiddleware } from "./middlewares/cors";
import MainRouter from "./routes/index";
import { authenticate } from "./middlewares/auth";

dotenv.config();

const app = express();
const PORT = process.env.PORT || 3000;
app.use(cors());
// 添加静态文件服务中间件，将当前目录作为静态资源目录
app.use(express.static(__dirname));
initDbRoutes(app);

const whitelist = [
  "/api/auth/login",
  "/api/auth/refresh-token",
  "/public",
  "/api/posts",
  "/api/users",
  "/api/db1",
  "/api/db2",
  // "/api/main/users",
  // 暂时开放上传功能,后续进行身份验证,避免任意用户上传图片,暴露图片路径
  "/upload",
  "/test.html"
];
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 请求日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
  next();
});

// 身份验证中间件
app.use((req, res, next) => {
  if (whitelist.some((route) => req.path.startsWith(route))) {
    return next();
  }
  authenticate(req, res, next);
});

app.use("/api/auth", authRoutes);
app.use("/", uploadRoutes);
app.use("/api", MainRouter);

// 全局错误处理中间件
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
  console.error('全局错误处理捕获到错误:', err);
  res.status(500).json({
    error: '服务器内部错误',
    message: err.message,
    stack: process.env.NODE_ENV === 'development' ? err.stack : undefined
  });
});

app.listen(PORT, () => {
  console.log(`服务器已启动，运行在端口 ${PORT}`);
  console.log(`环境变量检查:`);
  console.log(`- PORT: ${process.env.PORT ? '已设置' : '未设置，使用默认值 3000'}`);
  console.log(`- GITEE_TOKEN: ${process.env.GITEE_TOKEN ? '已设置' : '未设置 ⚠️'}`);
  console.log(`- GITEE_OWNER: ${process.env.GITEE_OWNER ? '已设置' : '未设置 ⚠️'}`);
  console.log(`- GITEE_REPO: ${process.env.GITEE_REPO ? '已设置' : '未设置 ⚠️'}`);
  console.log(`- GITEE_BRANCH: ${process.env.GITEE_BRANCH ? '已设置' : '未设置，使用默认值 main'}`);
});
